package com.zhiyou.controller.rentController;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhiyou.bean.Rent;
import com.zhiyou.service.Rent.Rentservice;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.crypto.dsig.keyinfo.PGPData;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@Controller
public class RentController {
    @Autowired
    Rentservice rentservice;

    @RequestMapping("/rentlist")
    public String rent( @RequestParam(name="pn",defaultValue = "1") Integer pn,Map<String,PageInfo> map){
       PageHelper.startPage(pn, 5 );
        List<Rent> list = rentservice.selectGetAll(pn);
       PageInfo page = new PageInfo( list, 5);
        map.put("pageInfo",page);
        //1234
        return "rentlist";
    }
    //rentList跳转的rentAdd的页面
    @RequestMapping("/rentadd")
    public String rentadd(){
        return "rentadd";
    }

    @RequestMapping("/rentadd2")
    public String rentAdd(Rent rent){
        int i = rentservice.AddRent(rent);
        System.out.println("i="+i);
        return "redirect:/rentlist";
    }
    //页面详情
    @RequestMapping("/rentdetail")
    public String rentdetail(String  rid ,Map<String,Rent> map1){
        List<Rent> rent = rentservice.getAllDetail(rid);
        Rent rent1 = rent.get(0);
        map1.put("rent",rent1);
        return "rentdetail";
    }
    //页面编辑
    @RequestMapping("rentedit")
    public String rentedit(String rid, Map<String,Rent> map ){
        List<Rent> allEdit = rentservice.getAllEdit(rid);
        Rent rent = allEdit.get(0);
        map.put("rent",rent);
        return "rentedit";
    }
    //页面编辑跳转
    @RequestMapping("change")
    public String rentedit1(Rent rent)  {
        rentservice.UpdateRent(rent);
        return "redirect:/rentlist";
    }
    //页面删除
    @RequestMapping("rentdelete")
    public String RentDelete(String  rid){
        int i = rentservice.DeleteRent(rid);
        System.out.println("rent="+i);
        return "redirect:/rentlist";
    }

    //查询数据
    @RequestMapping("select")
    public String RentSelect(@RequestParam(name="pn",defaultValue = "1") Integer pn, String field, String ID, Map<String, PageInfo> map, HttpSession session){
        if(ID == null){
            session.removeAttribute("field");
            session.removeAttribute("selId");
        }else{
            session.setAttribute("field",field);
            session.setAttribute("selId",ID);
        }
        PageHelper.startPage(pn, 5 );
        List<Rent> list = rentservice.getLikeRent((String) session.getAttribute("field"),(String) session.getAttribute("selId"));
        PageInfo page = new PageInfo( list, 5);
        map.put("pageInfo",page);
        return "rentlist";
    }
//    /**
//     *
//     * @param uploadFile
//     * @return
//     * Excel导入到数据库
//     */
//    @RequestMapping("/importExcel")
//    public ResResult importEmps(MultipartFile uploadFile){
//        ResResult result=new ResResult();
//        try {
//            //workbook excel
//            Workbook workbook=new XSSFWorkbook(uploadFile.getInputStream());
//            //获取excel的第一个sheet
//            Sheet sheet=workbook.getSheetAt(0);
//            //获取最后一行的下标
//            int lastRowNum=sheet.getLastRowNum();
//            List<Employee> emps=new ArrayList<>();
//            for (int i = 1; i <=lastRowNum ; i++) {
//                //获取第i行
//                Row row=sheet.getRow(i);
//                //获取本行的最后一个单元格的下标
//                short lastCellNum=row.getLastCellNum();
//                Object[] obs=new Object[lastCellNum];
//                for (int j = 0; j <lastCellNum ; j++) {
//                    //获取第i行的 第j个 单元格
//                    Cell cell=row.getCell(j);
//                    System.out.println("cell: "+cell);
//                    //拿到单元格的 value值
//                    Object value=ExcelUtils.getValue(cell);
//                    obs[j]=value;
//
//                }
//                //把从excel中拿出来的数据封装到 对象中
//                Employee employee=new Employee();
//                employee.setEmpno((String) obs[0]);
//                employee.setName((String) obs[1]);
//                employee.setSex((String) obs[2]);
//                employee.setAge(((Double)obs[3]).intValue());
//                employee.setJob((String) obs[4]);
//                employee.setDepartid(((Double)obs[5]).intValue());
//                //把对象放到list
//                emps.add(employee);
//            }
//            //保存
//            excelService.importExcel(emps);
//            result.setMsg(200);
//        }catch (Exception e){
//            e.printStackTrace();
//            result.setMsg(500);
//        }
//        return  result;
//    }

    /**
     * 导出excel
     */
    @RequestMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response, Model model){
        List<Rent> emps = rentservice.selectGetAll();
        //新建一个Excel 对象
        //把weorkbook对象  理解为一个 excel
        Workbook workbook=new XSSFWorkbook();
        //在excel中创建一个 sheet
        Sheet sheet=workbook.createSheet("一月");
        String[] titles={"房租序号","房子序号","房子地址","房子面积","租户序号","租户姓名","租户手机号","租户身份证号","房租总额","房租支付时间","备注"};
        //创建一行
        Row row=sheet.createRow(0);
        for (int i = 0; i <titles.length ; i++) {
            //cell 是一个单元格
            Cell cell=row.createCell(i);
            //往单元格里面放数据
            cell.setCellValue(titles[i]);
        }
        for (int i = 0; i <emps.size() ; i++) {
            row=sheet.createRow(i+1);
            Rent employee=emps.get(i);
            Cell empnoCell=row.createCell(0);
            empnoCell.setCellValue(employee.getrId());
            Cell nameCell=row.createCell(1);
            nameCell.setCellValue(employee.getHouse().gethId());
            Cell sexCell=row.createCell(2);
            sexCell.setCellValue(employee.getHouse().gethAddress());
            Cell ageCell=row.createCell(3);
            ageCell.setCellValue(employee.getHouse().gethAcreage());
            Cell jobCell=row.createCell(4);
            jobCell.setCellValue(employee.getLessee().getlId());
            Cell departidCell=row.createCell(5);
            departidCell.setCellValue(employee.getLessee().getlName());
            Cell ltelcell = row.createCell(6);
            ltelcell.setCellValue(employee.getLessee().getlTel());
            Cell lidcardcell = row.createCell(7);
            lidcardcell.setCellValue(employee.getLessee().getlIdcard());
            Cell rmoneycell = row.createCell(8);
            rmoneycell.setCellValue(employee.getrMoney());
            Cell rtimecell = row.createCell(9);
            rtimecell.setCellValue(employee.getrTime());
            Cell rremarkcell = row.createCell(10);
            rremarkcell.setCellValue(employee.getrRemark());

        }
        try {
            String fileName= URLEncoder.encode("员工表.xlsx","UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("content-disposition","attachment;filename="+fileName);
            response.setHeader("filename",fileName);
            //把workbook对象 写出去，到 response的输出流
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

//    /**
//     * 生成模板格式的Excel
//     */
//    @RequestMapping("/exportExcelStyle")
//    public void exportExcelStyle(HttpServletResponse response) throws IOException {
//        List<Employee> employees = excelService.exportExcel();
//        Workbook workbook=new XSSFWorkbook(Objects.requireNonNull(EmpController.class.getClassLoader().getResourceAsStream("excel/emps2.xlsx")));
//        Sheet sheet=workbook.getSheetAt(0);
//        Row row1=sheet.getRow(2);
//        //获取模板的样式
//        CellStyle[] cellStyle=new CellStyle[row1.getLastCellNum()];
//        for (int i = 0; i <cellStyle.length ; i++) {
//            cellStyle[i]=row1.getCell(i).getCellStyle();
//        }
//        for (int i = 0; i <employees.size() ; i++) {
//            Row row=sheet.createRow(i+2);
//            Employee employee = employees.get(i);
//            Cell empnoCell=row.createCell(0);
//            empnoCell.setCellValue(employee.getEmpno());
//            empnoCell.setCellStyle(cellStyle[0]);
//            Cell nameCell=row.createCell(1);
//            nameCell.setCellValue(employee.getName());
//            nameCell.setCellStyle(cellStyle[1]);
//            Cell sexCell=row.createCell(2);
//            sexCell.setCellValue(employee.getSex());
//            sexCell.setCellStyle(cellStyle[2]);
//            Cell ageCell=row.createCell(3);
//            ageCell.setCellValue(employee.getAge());
//            ageCell.setCellStyle(cellStyle[3]);
//
//            Cell jobCell=row.createCell(4);
//            jobCell.setCellValue(employee.getJob());
//            jobCell.setCellStyle(cellStyle[4]);
//
//            Cell departidCell=row.createCell(5);
//            departidCell.setCellValue(employee.getDepartid());
//            departidCell.setCellStyle(cellStyle[5]);
//
//        }
//        String fileName=URLEncoder.encode("员工表2.xlsx","UTF-8");
//        response.setContentType("application/octet-stream");
//        response.setHeader("content-disposition","attachment;filename="+fileName);
//        response.setHeader("filename",fileName);
//        workbook.write(response.getOutputStream());
//    }


}
